import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_yn_goods/config/app_color.dart';
import 'package:flutter_yn_goods/config/app_routes.dart';
import 'package:flutter_yn_goods/config/app_theme.dart';
import 'package:flutter_yn_goods/config/app_translations.dart';
import 'package:flutter_yn_goods/generated/assets.dart';
import 'package:flutter_yn_goods/pages/goods_info/comment_list/model/model_comment_list.dart';
import 'package:flutter_yn_goods/user/app_user_manager.dart';
import 'package:flutter_yn_goods/utils/log/utils_log.dart';
import 'package:flutter_yn_goods/widgets/appbar/common_app_bar.dart';
import 'package:flutter_yn_goods/widgets/image/auto_image.dart';
import 'package:flutter_yn_goods/widgets/image/image_view.dart';
import 'package:flutter_yn_goods/widgets/widget_line.dart';
import 'package:flutter_yn_goods/widgets/widget_share_dialog.dart';
import 'package:get/get.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'goods_info_logic.dart';

class GoodsInfoPage extends StatelessWidget {
  GoodsInfoPage({Key? key}) : super(key: key);

  final GoodsInfoLogic logic = Get.put(GoodsInfoLogic());

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.colorF6F8FB,
      body: Obx(() {
        return Stack(
          children: [
            Positioned.fill(
                child: SingleChildScrollView(
              // padding: EdgeInsets.only(bottom: 16.w),
              controller: logic.scrollController,
              child: Column(
                children: [
                  _buildCarouselSlider(),
                  Container(
                    color: Colors.white,
                    width: 1.sw,
                    padding:
                        EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.w),
                    child: Column(
                      children: [
                        Text(
                          logic.goodsInfoRx.value.storeInfo?.storeName ?? '',
                          style: TextStyle(
                              color: AppColor.color282828,
                              fontSize: 14.sp,
                              fontWeight: FontWeight.w500),
                        ),
                        SizedBox(height: 8.h),
                        Row(
                          children: [
                            Text(
                              '${LocaleKeys.product_id.tr}: ',
                              style: TextStyle(
                                color: AppColor.color666666,
                                fontSize: 12.sp,
                              ),
                            ),
                            Text(
                              logic.goodsInfoRx.value.storeInfo?.id?.toString() ?? '',
                              style: TextStyle(
                                color: AppColor.color282828,
                                fontSize: 12.sp,
                              ),
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),


                  // 评论板块
                  _buildReviewSection(),
                  SizedBox(height: 10.h),

                  ...logic.goodsInfoRx.value.getImage().map((element) {
                    return ImageView(
                      imageUrl: element,
                      width: 1.sw,
                    );
                  }),
                  // 添加底部占位空间，给底部按钮留出空间
                  SizedBox(height: 60.h),
                ],
              ),
            )),
            Positioned(
                top: 0,
                left: 0,
                right: 0,
                child: Obx(() {
                  return CommonAppBar(
                    title: logic.goodsInfoRx.value.storeInfo?.storeName ?? '',
                    actions:
                        // AppUserManager().isLeader()
                        //     ?
                        [
                      GestureDetector(
                        onTap: () {
                          // Get.toNamed(AppRoutes.commentListPage,
                          //     arguments: logic.goodsInfoRx.value.storeInfo?.id);
                          //
                          // return;

                          if (AppUserManager().isLogin) {
                            WidgetShareDialog(
                              img: logic.goodsInfoRx.value.storeInfo
                                      ?.sliderImage?.firstOrNull ??
                                  '',
                              price: logic.goodsInfoRx.value.storeInfo?.price ??
                                  '',
                              title: logic
                                      .goodsInfoRx.value.storeInfo?.storeName ??
                                  '',
                              goodsId:
                                  (logic.goodsInfoRx.value.storeInfo?.id ?? '')
                                      .toString(),
                            ).show();
                          } else {
                            Get.toNamed(AppRoutes.login);
                          }
                        },
                        child: Container(
                          width: 44,
                          height: 44,
                          alignment: Alignment.center,
                          child: AutoImage(
                            Assets.iconShare,
                            width: 24.w,
                          ),
                        ),
                      )
                    ],
                    backgroundColor:
                        Colors.white.withOpacity(logic.appBarOpacity.value),
                  );
                })),
            // 底部操作栏
            Positioned(
              bottom: 0,
              left: 0,
              right: 0,
              child: _buildBottomBar(),
            ),
          ],
        );
      }),
    );
  }

  Widget _buildCarouselSlider() {
    return (logic.goodsInfoRx.value.storeInfo?.sliderImage ?? []).isEmpty
        ? SizedBox(
            height: 1.sw,
          )
        : CarouselSlider.builder(
            itemCount:
                (logic.goodsInfoRx.value.storeInfo?.sliderImage ?? []).length,
            // carouselController: logic.carouselController,
            itemBuilder: (BuildContext context, int index, int realIndex) {
              return ImageView(
                imageUrl: (logic.goodsInfoRx.value.storeInfo?.sliderImage ??
                    [])[index],
                width: 1.sw,
                height: 1.sw,
              );
            },
            options: CarouselOptions(
              height: 1.sw,
              viewportFraction: 1,
              // enlargeFactor: 0,
              enlargeCenterPage: true,
              // initialPage: logic.currentPlayRx.value,
              enableInfiniteScroll: true,
              // autoPlay: false,
              onPageChanged: (int count, CarouselPageChangedReason reason) {
                // logic.changePlayPodcast(count);
                // clog('onPageChanged   $count  reason  ${reason.name}  ');
              },
            ),
          );
  }

  // 底部操作栏
  Widget _buildBottomBar() {
    return Container(
      height: 50.h,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Colors.black.withOpacity(0.05),
            blurRadius: 4,
            offset: Offset(0, -1),
          ),
        ],
      ),
      child: Row(
        children: [
          // 收藏按钮
          Expanded(
            flex: 1,
            child: InkWell(
              onTap: () {
                logic.toggleCollect();
              },
              child: Obx(() => Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(
                        logic.isCollected.value
                            ? Icons.favorite
                            : Icons.favorite_border,
                        color:
                            logic.isCollected.value ? Colors.red : Colors.grey,
                        size: 24.w,
                      ),
                      Text(
                        logic.isCollected.value
                            ? LocaleKeys.collected.tr
                            : LocaleKeys.collect.tr,
                        style: TextStyle(
                          fontSize: 12.sp,
                          color: AppColor.color282828,
                        ),
                      ),
                    ],
                  )),
            ),
          ),
          // "我想要"按钮
          Expanded(
            flex: 2,
            child: GestureDetector(
              onTap: () {
                logic.addToCollect(isWant: true);
              },
              child: Container(
                height: 50.h,
                alignment: Alignment.center,
                color: AppColor.primary,
                child: Text(
                  LocaleKeys.i_want_this.tr,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  // 评论板块
  Widget _buildReviewSection() {
    final commentConfig = logic.commentConfigRx.value;
    final commentList = logic.commentListRx;

    // 如果没有评论数据，不显示评论板块
    // if (commentList.isEmpty) {
    //   return const SizedBox();
    // }

    return Container(
      color: Colors.white,
      width: 1.sw,
      margin: EdgeInsets.only(top: 10.h),
      padding: EdgeInsets.all(16.w),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 评论板块标题
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                LocaleKeys.reviews.tr,
                style: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                  color: AppColor.color282828,
                ),
              ),
              InkWell(
                onTap: () {
                  Get.toNamed(AppRoutes.commentListPage,
                      arguments: logic.goodsInfoRx.value.storeInfo?.id);
                },
                child: Row(
                  children: [
                    Text(
                      LocaleKeys.view_all_reviews.tr,
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: AppColor.color666666,
                      ),
                    ),
                    Icon(
                      Icons.arrow_forward_ios,
                      size: 12.sp,
                      color: AppColor.color666666,
                    ),
                  ],
                ),
              ),
            ],
          ),
          SizedBox(height: 16.h),

          // 评论统计信息
          Row(
            children: [
              // 左侧评分和满意度
              Expanded(
                flex: 2,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text(
                      commentConfig.replyStar ?? '0',
                      style: TextStyle(
                        fontSize: 28.sp,
                        fontWeight: FontWeight.bold,
                        color: AppColor.primary,
                      ),
                    ),
                    SizedBox(height: 4.h),
                    _buildRatingStars(
                        int.parse(commentConfig.replyStar ?? '0')),
                    SizedBox(height: 8.h),
                    Text(
                      '${LocaleKeys.satisfaction_rate.tr}: ${commentConfig.replyChance ?? '0'}%',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: AppColor.color666666,
                      ),
                    ),
                  ],
                ),
              ),

              // 右侧评价数量统计
              Expanded(
                flex: 3,
                child: Column(
                  children: [
                    _buildReviewCountItem(
                      LocaleKeys.total_reviews.tr,
                      commentConfig.sumCount ?? 0,
                    ),
                    SizedBox(height: 8.h),
                    _buildReviewCountItem(
                      LocaleKeys.positive_reviews.tr,
                      commentConfig.goodCount ?? 0,
                      color: Colors.green,
                    ),
                    SizedBox(height: 8.h),
                    _buildReviewCountItem(
                      LocaleKeys.medium_reviews.tr,
                      commentConfig.inCount ?? 0,
                      color: Colors.orange,
                    ),
                    SizedBox(height: 8.h),
                    _buildReviewCountItem(
                      LocaleKeys.negative_reviews.tr,
                      commentConfig.poorCount ?? 0,
                      color: Colors.red,
                    ),
                  ],
                ),
              ),
            ],
          ),

          // 分隔线
          Padding(
            padding: EdgeInsets.symmetric(vertical: 16.h),
            child: Divider(height: 1, color: AppColor.colorEBECF1),
          ),

          // 评论列表
          ...commentList.map((item) => _buildCommentItem(item)),
        ],
      ),
    );
  }

  // 评分星星
  Widget _buildRatingStars(int score) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(5, (index) {
        return Icon(
          index < score ? Icons.star : Icons.star_border,
          color: index < score ? AppColor.colorFFAE4A : AppColor.colorCFD2D9,
          size: 16.sp,
        );
      }),
    );
  }

  // 评价数量项
  Widget _buildReviewCountItem(String label, int count, {Color? color}) {
    return Row(
      children: [
        Expanded(
          flex: 2,
          child: Text(
            label,
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColor.color666666,
            ),
          ),
        ),
        Expanded(
          flex: 3,
          child: Text(
            count.toString(),
            style: TextStyle(
              fontSize: 12.sp,
              color: color ?? AppColor.color282828,
              fontWeight: color != null ? FontWeight.bold : FontWeight.normal,
            ),
          ),
        ),
      ],
    );
  }

  // 评论项
  Widget _buildCommentItem(ModelCommentList item) {
    return Padding(
      padding: EdgeInsets.only(bottom: 16.h),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户信息

          Row(
            children: [
              ClipOval(
                child: item.avatar != null && item.avatar!.isNotEmpty
                    ? Image.network(
                        item.avatar!,
                        width: 40.w,
                        height: 40.w,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return Container(
                            width: 40.w,
                            height: 40.w,
                            color: AppColor.colorEBECF1,
                            child: Icon(Icons.person,
                                color: Colors.grey, size: 24.w),
                          );
                        },
                      )
                    : Container(
                        width: 40.w,
                        height: 40.w,
                        color: AppColor.colorEBECF1,
                        child:
                            Icon(Icons.person, color: Colors.grey, size: 24.w),
                      ),
              ),
              SizedBox(width: 10.w),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      item.nickname ?? LocaleKeys.anonymous.tr,
                      style: TextStyle(
                        fontSize: 14.sp,
                        fontWeight: FontWeight.w500,
                        color: AppColor.color202020,
                      ),
                    ),
                    SizedBox(height: 4.h),
                    Text(
                      item.addTimeText ?? '',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: AppColor.color999999,
                      ),
                    ),
                  ],
                ),
              ),
              // 评分展示
              _buildRatingStars(item.productScore ?? 5),
            ],
          ),
          SizedBox(height: 12.h),

          // 评论内容
          if (item.comment != null && item.comment!.isNotEmpty)
            Text(
              item.comment!,
              style: TextStyle(
                fontSize: 14.sp,
                color: AppColor.color202020,
                height: 1.5,
              ),
              maxLines: 3,
              overflow: TextOverflow.ellipsis,
            ),

          // 评论图片
          if (item.pics != null && item.pics!.isNotEmpty) ...[
            SizedBox(height: 8.h),
            _buildCommentImages(item.pics!),
          ],

          // 商家回复
          if (item.merchantReply != null && item.merchantReply!.isNotEmpty) ...[
            SizedBox(height: 8.h),
            Container(
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: AppColor.colorF5F5F5,
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    LocaleKeys.merchant_reply.tr,
                    style: TextStyle(
                      fontSize: 12.sp,
                      fontWeight: FontWeight.w500,
                      color: AppColor.color666666,
                    ),
                  ),
                  SizedBox(height: 4.h),
                  Text(
                    item.merchantReply!,
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: AppColor.color666666,
                      height: 1.5,
                    ),
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 评论图片
  Widget _buildCommentImages(List<String> images) {
    return SizedBox(
      height: 80.w,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: images.length > 3 ? 3 : images.length,
        itemBuilder: (context, index) {
          return Container(
            width: 80.w,
            height: 80.w,
            margin: EdgeInsets.only(right: 8.w),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(4.r),
              image: DecorationImage(
                image: NetworkImage(images[index]),
                fit: BoxFit.cover,
              ),
            ),
          );
        },
      ),
    );
  }
}
